package com.zzh.zookeeper.demo;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @PackageName:com.zzh.zookeeper.demo
 * @ClassName:ZookeeperDemo
 * @Description:
 * @author:zhangzhanheng
 * @date: 2020/12/17 11:16
 */
public class ZookeeperDemo {
    private static final String address = "39.106.120.188:2181";
    private static final int session_timeout = 5000;
    private static final CountDownLatch cout = new CountDownLatch(1);

    public static void main(String[] args) {
        Watcher watcher;
        ZooKeeper zk = null;
        try {
            zk = new ZooKeeper(address, session_timeout, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    Event.KeeperState state = watchedEvent.getState();
                    if (Event.KeeperState.SyncConnected == state) {

                        Event.EventType type = watchedEvent.getType();
                        if (Event.EventType.None == type) {
                            cout.countDown();
                            System.out.println("开始连接");
                        }
                    }
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            cout.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String create = null;
        try {
            create = zk.create("/zzh","测试连接".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("-------创建节点： " + create);
        try {
            zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
